import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'
import {View, Text} from '@tarojs/components'
import CustomerInput from '@/components/Input/Input'
import PageLoading from '@/components/PageLoading/PageLoading'
import Loading from '@/components/Loading/Loading'
import {getSearchSight} from '@/services/home'
import {SightInfo, SightInfoRet} from '@/type'
import Taro, {useReachBottom, useReady} from '@tarojs/taro'
import {useDebounce} from '@/hooks'
import './Search.scss'

/**
 * 搜索 分页
 */
const useSearchList = (word, setHistory) => {
  let [searchList, setSearchList] = useState<SightInfo[]>([])
  const preWord = useRef(word)
  const [more, setMore] = useState(true)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(1)

  useEffect(() => {
    setPage(1)
    setTotal(1)
    setSearchList([])
  }, [word])

  useEffect(() => {
    if (!word) return
    getSearchSight(word, {
      page, size: 20
    }).then((res: SightInfoRet) => {
      setHistory(word)
      if (preWord.current === word) {
        setSearchList(preSearchList => preSearchList.concat(res.records))
      } else {
        setSearchList(res.records)
      }
      setTotal(res.pages)
      preWord.current = word
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, word])

  useReachBottom(() => {
    if (page < total) {
      setPage(prePage => prePage + 1)
      setMore(true)
    } else {
      setMore(false)
    }
  })

  return {
    searchList,
    more
  }
}

/**
 * history
 */
const useHistory = () => {
  const [historyList, setHistoryList] = useState<string[]>([])
  useReady(() => {
    let searchHistory = Taro.getStorageSync('searchHistory') || []
    setHistoryList(searchHistory)
  })

  const setHistory = useCallback((value) => {
    let history = Taro.getStorageSync('searchHistory') || []
    if(Array.isArray(history) && !history.includes(value)) {
      history.push(value)
    }
    setHistoryList(history)
    Taro.setStorageSync('searchHistory', history)
  }, [])

  return {
    historyList,
    setHistory
  }
}

const Search: React.FC = () => {
  const [searchVal, setSearchVal] = useState('')
  const debounce = useDebounce(searchVal)
  const {historyList, setHistory} = useHistory()

  const {searchList, more} = useSearchList(debounce, setHistory)

  function onSearchInput (e) {
    setSearchVal(e.detail.value)
  }

  /**
   * 事件代理
   * @param e
   */
  function onselect (e) {
    let id = e.target.dataset?.id
    if (id) {
      Taro.navigateTo({
        url: `/packageA/pages/Scene/Scene?id=${id}`
      })
    }
  }

  function onselectHistory (e) {
    let history = e.target.dataset.history
    if (history) {
      setSearchVal(history)
    }
  }

  /**
   * 底部loading
   */
  const LoadingComputed = useMemo(() => {
    let n = searchList.length
    if (more && n >= 20) {
      return <View className='search_list_item'>
        <Loading />
      </View>
    }
    if (n >= 20) {
      return <View className='search_list_item' style={{justifyContent: 'center'}}>已经到底了~~~</View>
    }
    return <></>
  }, [more, searchList])

  return <View className='search_wrap'>
    <View className='search_wrap_nav'>
      <View className='back iconfont' onClick={() => Taro.navigateBack()}>&#xe610;</View>
      <View className='search_wrap_input'>
        <CustomerInput
          searchVal={searchVal}
          onsearchInput={onSearchInput}
          focus
          className='customer_input'
          placeholder='居家美食实用手册'
        />
      </View>
      {/*<View className='search_btn'>搜索</View>*/}
    </View>
    <View className='history_wrap' style={{display: !searchVal && historyList.length ? 'block' : 'none'}}>
      <View className='history_wrap_title search_title'>历史记录</View>
      <View className='history_wrap_list'
        onClick={onselectHistory}
      >
        {
          historyList.map((history, index) => <View key={index}
            className='history_wrap_list_item'
            data-history={history}
          >
            {history}
          </View>)
        }
      </View>
    </View>
    <View className='find_wrap' style={{display: 'none'}}>
      <View className='find_wrap_title search_title'>搜索发现</View>
    </View>

    <View className='search_list' style={{display: searchVal ? 'block' : 'none'}}
      onClick={onselect}
    >
      {
        searchList.length ? <View>
          {
            searchList.map(searchItem => <View className='search_list_item' data-id={searchItem.id} key={searchItem.id}>
              <Text data-id={searchItem.id}  className='search_list_item_title'>{searchItem.name}</Text>
            </View>)
          }
          {LoadingComputed}
        </View> : <PageLoading />
      }
    </View>
  </View>
}

export default Search
